import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';
import { HttpErrorResponse } from '@angular/common/http';
import {MatSnackBar} from '@angular/material';

import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';

import { AuthService } from '../../auth.service';
import { BlogService } from '../../blog.service';

@Component({
  selector: 'app-blog-content',
  templateUrl: './blog-content.component.html',
  styleUrls: ['./blog-content.component.scss']
})
export class BlogContentComponent implements OnInit {
  codeBackup: string;
  code: string;
  file: Observable<string>;
  isOnLoading = true;
  isChanged: boolean;
  private markTerms = new Subject<string>();

  constructor(
    public snackBar: MatSnackBar,
    private activatedRoute: ActivatedRoute,
    private location: Location,
    public authService: AuthService,
    private blogService: BlogService
  ) { }

  ngOnInit() {
    this.file = this.markTerms
      .debounceTime(300)
      .distinctUntilChanged()
      .switchMap(code => this.blogService.markedContent(code));

    this.activatedRoute.params
      .switchMap((params: Params) => {
        this.isOnLoading = true;
        return this.blogService.getFile(params['dir'], params['file'])
      }).subscribe(file => {
        this.code = file;
        this.codeBackup = file;
        this.mark(file);
        this.isOnLoading = false;
      }, (err: HttpErrorResponse) => {
        if (err.error instanceof Error) {
          this.file = Observable.of<string>(err.error.message);
        } else {
          this.file = Observable.of<string>(err.status + " " + err.statusText);
        }
      });
  }

  mark(code: string): void {
    this.markTerms.next(code);
    this.checkFileChangs();
  }

  updateFileContent(): void {
    this.blogService.getFileContent(this.location.path())
      .subscribe(fileContent =>
        this.blogService.updateFile(fileContent, this.code)
          .subscribe(updateResult => {
            this.codeBackup = this.code;
            this.checkFileChangs();
            this.snackBar.open("保存成功！", "", {
              duration: 600,
            });
          }, (err: HttpErrorResponse) => this.handleError(err)),
          (err: HttpErrorResponse) => this.handleError(err)
      );
  }

  handleError(err: HttpErrorResponse): void {
    if (err.error instanceof Error) {
      this.snackBar.open(err.error.message, "", {
        duration: 1000,
      });
    } else {
      this.snackBar.open(err.status + " " + err.statusText, "", {
        duration: 1000,
      });
    }
  }

  checkFileChangs(): void {
    this.isChanged = this.code != this.codeBackup;
  }
}
